package com.yonyou.crm.base.attr.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.base.attr.entity.AttrBVO;
import com.yonyou.crm.base.attr.entity.AttrVO;
import com.yonyou.crm.base.attr.rmitf.IAttrRmService;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;

@RestController
@RequestMapping(value = "/base/attrs")
public class AttrCtrl {

	@Autowired
	private IAttrRmService service;
	
	/**
	 * 查询属性
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);

		@SuppressWarnings("unchecked")
		Page<AttrVO> rPage = service.page(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(rPage);
	}
	
	/**
	 * 属性详情
	 * @param code
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}		
		
		return ResponseUtil.getObject(service.detail(id));
	}
	
	/**
	 * 新增属性
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		AttrVO vo = getAttrVO(request);

		String validMsg = insertValidator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
				
		return ResponseUtil.getObject(service.insert(vo));
	}
	
	/**
	 * 修改属性
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}
		
		AttrVO vo = getAttrVO(request);

		String validMsg = updateValidator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		vo.setId(id);
				
		return ResponseUtil.getObject(service.update(vo));
	}
	
	/**
	 * 批量删除
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] ids = idsStr.split(",");
		
		if (ids.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		String message = service.batchDelete(ids);
		
		Page<AttrVO> page = service.page(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(page, PCCodeConstant.Success, message);
	}
	
	/**
	 * 批量停启用
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "state", method = RequestMethod.PUT)
	public Object batchUpdateEnableState(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] ids = idsStr.split(",");
		
		if (ids.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		Integer enableState = paramObj.getInt("enableState");
		
		if (enableState == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "停启用状态不能为空");
		}
						
		return ResponseUtil.getObject(service.batchUpdateEnableState(ids, enableState, getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap")));
	}
	
	/**
	 * 获得属性参照列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ref", method = RequestMethod.GET)
	public Object attrRefList(HttpServletRequest request, HttpServletResponse response) {
		
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("voList", service.getAttrRefList());
		
		return ResponseUtil.getObject(rMap);
	}
	
	/**
	 * 获得属性值参照列表
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}/values/ref", method = RequestMethod.GET)
	public Object attrValueRefList(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "属性主键不能为空");
		}
		
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("voList", service.getAttrValueRefList(id));
		
		return ResponseUtil.getObject(rMap);
	}
	
	/**
	 * 被属性组引用的属性值
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/{id}/cited", method = RequestMethod.GET)
	public Object cited(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "属性主键不能为空");
		}
		
		JSONObject rObj = new JSONObject();

		List<String> idList = service.getIdsByAttrGroup(id);
		rObj.put("ids", idList);
		
		return ResponseUtil.getObject(rObj);
	}
	
	private Page<AttrVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {
		
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		
		return new Page<AttrVO>(page, pageSize);
	}
	
	private String insertValidator(AttrVO vo) {
		
		if (vo == null) {
			return "转换实体失败";
		}
		
		if (StringUtils.isBlank(vo.getName())) {
        	return  "名称不能为空";
		}
		
		if (vo.getValueList() == null || vo.getValueList().size() == 0) {
			return "至少包含一个属性值";
		}

		for (AttrBVO bVO : vo.getValueList()) {
			if (bVO.getValue() == null) {
				return "属性值不能为空";
			}
		}
		
		return "";
	}
	
	private String updateValidator(AttrVO vo) {
		
		if (vo == null) {
			return "转换实体失败";
		}
		
		if (StringUtils.isBlank(vo.getName())) {
        	return  "名称不能为空";
		}
		
		return "";
	}
	
	private AttrVO getAttrVO(HttpServletRequest request) {
		
		Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
		fieldClassMap.put("valueList", AttrBVO.class);
		return RequestUtil.getVO(request, AttrVO.class, fieldClassMap);
	}
}
